#include <disp_manager.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/fb.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
 
static int fd_fb;
static struct fb_var_screeninfo var;	/* 获取设备信息的结构体 */
static int screen_size;
static unsigned char *fb_base;
static unsigned int line_width;
static unsigned int pixel_width;
 

 
static int FbDeviceInit(void)
{//初始化FrameBuffer，获取设备信息
	fd_fb = open("/dev/fb0", O_RDWR);
	if (fd_fb < 0)
	{
		printf("can't open /dev/fb0\n");
		return -1;
	}
	if (ioctl(fd_fb, FBIOGET_VSCREENINFO, &var))
	{
		printf("can't get var\n");
		return -1;
	}
 
    line_width  = var.xres * var.bits_per_pixel / 8;
	pixel_width = var.bits_per_pixel / 8;
	screen_size = var.xres * var.yres * var.bits_per_pixel / 8;
	fb_base = (unsigned char *)mmap(NULL , screen_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_fb, 0);
	if (fb_base == (unsigned char *)-1)
	{
		printf("can't mmap\n");
		return -1;
	}
	return 0;
}
 
static int FbDeviceExit(void)
{//关闭设备
    munmap(fb_base, screen_size);
    close(fd_fb);
    return 0;
}
 
static int FbGetbuffer(PDispBuffer ptDispBuffer)// 获取显示内容buf的函数
{//获取FrameBuffer内存，返回起始地址
    ptDispBuffer->iXres = var.xres;
    ptDispBuffer->iYres = var.yres;
    ptDispBuffer->iBpp  = var.bits_per_pixel;
	ptDispBuffer->buf = (char *)fb_base;// mmap的来的虚拟映射空间
    return 0;
}
 
static int FbFlashRegion(PRegion ptRegion , PDispBuffer ptDisBuff)
{//显示
    return 0;
}
 
static DispOpr g_tFrameBuffer ={
    .name        = "fb",
    .DeviceInit  = FbDeviceInit ,
    .DeviceExit  = FbDeviceExit ,
    .Getbuffer   = FbGetbuffer ,
    .FlashRegion = FbFlashRegion ,
};

void FrameBufferInit(void)
{
	RegisterDisplayer(&g_tFrameBuffer);
}